<template>
  <RightTableLayout :slotName="['search', 'operation', 'table', 'pagination']">
    <template #search>
      <BaseSearch @querySearch="querySearch" :searchFields="searchFields"></BaseSearch>
    </template>
    <template #operation>
      <el-button @click="add">
        <el-icon>
          <DocumentAdd />
        </el-icon>{{ i18n.fy.新增 }}</el-button>
    </template>
    <template #table>
      <el-table :data="data.tableData" border v-loading="data.loading" :element-loading-text="i18n.fy.loading">
        <el-table-column prop="projectName" :label="i18n.language === 'zh-cn' ? '项目名称' : 'projectName'"
          align="center" />
        <el-table-column prop="projectStartTime" :label="i18n.language === 'zh-cn' ? '项目启动日期' : 'projectStartTime'"
          align="center" />
        <el-table-column prop="illuminance" :label="i18n.fy.改造后地面照度" align="center" />
        <el-table-column prop="originalIlluminance"
          :label="i18n.language === 'zh-cn' ? '改造前地面照度' : 'originalIlluminance'" align="center"> </el-table-column>
        <el-table-column prop="investmentAmount" :label="i18n.language === 'zh-cn' ? '总投资' : 'investmentAmount'"
          align="center"> </el-table-column>
        <el-table-column prop="attributes" :label="i18n.language === 'zh-cn' ? '客户属性' : 'attributes'" align="center">
        </el-table-column>
        <el-table-column prop="op" :label="i18n.language === 'zh-cn' ? '操作' : 'operate'" width="180" align="center">
          <template #default="scope">
            <a class="layui-btn layui-btn-xs" @click="uploadImg(scope.row)" :class="{ dsb: dsb != 2 }">
              {{ i18n.language === "zh-cn" ? "上传图片" : "Pictures" }}
            </a>
            <a class="layui-btn layui-btn-xs" @click="edit(scope.row)" :class="{ dsb: dsb != 2 }">
              {{ i18n.language === "zh-cn" ? "编辑" : "edit" }}
            </a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" @click="del(scope.row)">删除</a>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #pagination>
      <el-pagination @size-change="onChanSize" @current-change="onChanPage" v-model:current-page="data.queryForm.page"
        v-model:page-size="data.queryForm.limit" :total="data.total" />
    </template>
  </RightTableLayout>
  <div id="saveOrUpdateDiv" style="display: none; padding: 20px">
    <form class="layui-form1" lay-filter="dataFrm-" id="dataFrm">
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "项目名称" : "entryName" }}
          :</label>
        <div class="layui-input-block">
          <input type="text" v-model="data.form.projectName" name="rolename"
            :placeholder="i18n.language === 'zh-cn' ? '请输入项目名称' : 'Please enter a project name'" autocomplete="off"
            class="layui-input" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "项目启动日期" : "ProjectStartDate" }}
          :</label>
        <div class="layui-input-block">
          <div class="timeBtnBox">
            <input class="timeBtn" v-if="!pwdFlag && data.form.id" type="button" @click="checkTime" value="修改" />
            <el-date-picker ref="projectStartTime" class="timeDate" format="YYYY-MM-DD"
              value-format="YYYY-MM-DDTHH:mm:ss" v-model="data.form.projectStartTime" type="date"
              :placeholder="i18n.language === 'zh-cn' ? '请选择项目启动日期' : 'Please select the project start date'" />
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "改造前地面照度" : "Ground illumination before Renovation" }}

          :</label>
        <div class="layui-input-block">
          <input type="text" v-model="data.form.originalIlluminance"
            :placeholder="i18n.language === 'zh-cn' ? '请输入改造前地面照度' : 'Please input the ground illumination before the renovation'"
            autocomplete="off" class="layui-input" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.fy.改造后地面照度 }}
          :</label>
        <div class="layui-input-block">
          <input type="text" v-model="data.form.illuminance"
            :placeholder="i18n.language === 'zh-cn' ? '请输入改造后地面照度' : 'Please input the ground illumination after renovation'"
            autocomplete="off" class="layui-input" />
        </div>
      </div>

      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "客户属性" : "client property" }}
          :</label>
        <div class="layui-input-block">
          <el-select style="width: 100%" v-model="data.form.attributes" filterable allow-create default-first-option
            :reserve-keyword="false" placeholder="请选择客户属性">
            <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.companyName" />
          </el-select>
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.fy.项目总投资 }}:</label>
        <div class="layui-input-block">
          <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="data.form.investmentAmount"
            :placeholder="i18n.language === 'zh-cn' ? '请输入项目总投资' : 'Please enter the total investment of the project'">
            <template #append>万</template>
          </el-input>
        </div>
      </div>
      <div class="layui-form-item" v-show="data.form.id">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "所属用户" : "User" }}
          :</label>
        <div class="layui-input-block">
          <el-select filterable collapse-tags multiple style="width: 100%" v-model="users" class="m-2"
            :placeholder="i18n.language === 'zh-cn' ? '请选择用户' : 'Please select a user'" autocomplete="off">
            <el-option :disabled="showDisabled(item)" v-for="item in userOptions" :key="item.loginname"
              :label="item.loginname" :value="item.userid" />
          </el-select>
        </div>
      </div>

      <div class="layui-form-item">
        <label class="layui-form-label"> 电价/度 :</label>
        <div class="layui-input-block">
          <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="data.form.electricityPrice"
            placeholder="请输入电价">
            <template #append>元</template>
          </el-input>
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "项目状态" : "project state" }}
          :</label>
        <div class="layui-input-block">
          <el-select style="width: 100%" v-model="data.form.projectState" filterable allow-create default-first-option
            :reserve-keyword="false">
            <el-option v-for="item in projectstate" :key="item.id" :label="item.projectstate"
              :value="item.projectstate" />
          </el-select>
        </div>
      </div>

      <div class="layui-form-item">
        <label class="layui-form-label"> 单灯功耗 :</label>
        <div class="layui-input-block">
          <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="data.form.singleLampPower"
            placeholder="请输入改造前单灯功耗">
            <template #append>W</template>
          </el-input>
        </div>
      </div>

      <div class="layui-form-item">
        <label class="layui-form-label">{{ i18n.fy.项目地址 }} :</label>
        <!-- <div class="layui-input-block"> -->
        <div>
          <BaiduMapSearch @address-selected="onAddressSelected" :initialCoordinates="{
    lat: data.form.latitude,
    lng: data.form.longitude,
    address: data.form.address,
  }" />
        </div>
      </div>
      <div class="layui-form-item" v-show="data.form.id" style="width: 100%">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "选择设备" : "Select device" }}

          :</label>
        <div class="layui-input-block">
          <el-transfer @change="changeTransfer" filterable
            :titles="[i18n.language === 'zh-cn' ? '未激活设备' : 'DeviceNotActivated', i18n.language === 'zh-cn' ? '项目网关' : 'ProjectGateway']"
            v-model="transfervalue" :data="transferdata">
            <template #default="{ option }">
              <span v-if="option.label == null || option.label == ''">{{ option.key }}</span>
              <span>{{ option.label }}<b class="clickb"></b></span>
            </template>
          </el-transfer>
        </div>
      </div>
      <div class="layui-form-item" style="text-align: center; width: 100%; float: none; clear: both">
        <div class="layui-input-block">
          <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release"
            lay-filter="doSubmit" lay-submit="">
            {{ i18n.fy.提交 }}
          </button>
          <button type="reset" class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh">
            {{ i18n.fy.重置 }}
          </button>
        </div>
      </div>
    </form>
  </div>
  <div id="selectRoleMenu" style="display: none">
    <ul id="menuTree" class="dtree" data-id="0"></ul>
  </div>
  <el-dialog v-model="dialogVisible" title="提示" width="35%">
    <div style="height: 400px">
      <div class="tipsT">
        {{ strId }}
        <a href="javascript:void(0)" class="tag-read" :data-clipboard-text="strId" @click="copy">点击复制</a>
      </div>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="有线" name="first">
          <div class="tipsBox">
            <div class="tipsT">
              {{ str1 }}
              <a href="javascript:void(0)" class="tag-read" :data-clipboard-text="str1" @click="copy">点击复制</a>
            </div>
            <div class="tipsT">
              {{ str2 }}
              <a href="javascript:void(0)" class="tag-read" :data-clipboard-text="str2" @click="copy">点击复制</a>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="无线" name="second">
          <el-input v-model="textarea" autosize type="textarea" placeholder="" />
          <div>
            <a href="javascript:void(0)" class="tag-read" :data-clipboard-text="textarea" @click="copy">点击复制</a>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <div class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="dialogVisible = false"> 关闭 </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisible3" title="警告" width="30%">
    <div style="padding: 10px">
      <span style="color: red">修改项目启动日期可能会出现严重事故，请输入密码后修改</span>
      <div style="margin-top: 20px">
        <el-input v-model="pwd" placeholder="请输入密码" />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer" style="text-align: center; display: block">
        <el-button @click="dialogVisible3 = false">取消</el-button>
        <el-button type="primary" @click="enterPwd"> 确定修改 </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisibleImg">
    <div style="text-align: center; padding: 20px; padding-top: 0">
      <img :src="dialogImageUrl" alt="Preview Image" />
    </div>
  </el-dialog>
  <el-dialog title="上传项目图片" :close-on-click-modal="false" v-model="dialogTableVisible" width="800px"
    @close="closeDialog">
    <div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="项目图片" prop="binData">
          <el-input v-model="ruleForm.binData" style="height: 0px; overflow: hidden; display: none"></el-input>
          <div>
            <draggable v-model="fileList" class="drag_img" item-key="address">
              <template #item="{ element, index }">
                <div>
                  <div class="img_item">
                    <img :src="element.url" alt="" style="width: 100%; height: 100%" />
                    <div class="shade">
                      <div class="img_operate">
                        <el-icon>
                          <ZoomIn @click="handlePictureCardPreview(element)" style="cursor: pointer" />
                        </el-icon>
                        <el-icon style="margin: 0 10px">
                          <DeleteFilled @click="handleRemove(element)" style="cursor: pointer" />
                        </el-icon>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
              <template #footer>
                <el-upload :show-file-list="false" :data="{
    domain: ruleForm.domain,
    description: ruleForm.description,
  }" class="upload-demo" ref="upload" :action="imgAction" list-type="picture-card" :on-remove="handleRemove"
                  :on-preview="handlePictureCardPreview" :on-success="onSuccess" :file-list="fileList"
                  :auto-upload="true" :on-change="changeFile" :before-upload="beforeAvatarUpload">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </template>
            </draggable>
          </div>
        </el-form-item>
        <el-form-item>
          <div style="text-align: center">
            <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
            <el-button @click="closeDialog">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>
<script setup>
defineOptions({ name: "ProjectList" });
import RightTableLayout from "@/views/workbench/components/RightTableLayout.vue";
import BaiduMapSearch from "@/components/BaiduMapSearch.vue";
import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();
import BaseSearch from '@/views/workbench/components/BaseSearch.vue'
import Clipboard from "clipboard";
import axios from "axios";
import draggable from "vuedraggable";
import { getProjectList } from "@/api/systemmanageApi";
let searchFields = reactive([{ key: 'projectName', label: i18n.fy.项目名称, val: '' }])
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
let $httpUrl = globalProperties.$httpUrl;

let userOptions = ref([]);
let dialogTableVisible = ref(false);

const ruleForm = reactive({
  description: "",
  domain: "",
  binData: "",
});

const rules = reactive({
  description: [{ required: true, message: "请输入图片描述", trigger: "blur" }],
  domain: [{ required: true, message: "请输入公司网址", trigger: "blur" }],
  binData: [{ required: true, message: "请选择图片", trigger: "change" }],
});
const formState = ref("add")
const searchVal = ref("")
let data = reactive({
  queryForm: { page: 1, limit: 20 },
  tableData: [],
  total: 0,
  dialog: false,
  form: {
    isUserInput: false,
    projectStartTime: "",
    illuminance: "",
    originalIlluminance: "",
    investmentAmount: "",
    latitude: 39.915,
    address: null,
    longitude: 116.404,
    attributes: "",
    id: "",
    projectName: "",
    singleLampPower: "",
    projectLightInfos: [{ amount: "", power: "", lightName: "" }],
  },
  rules: {
    name: [{ required: true, message: "请输入姓名", trigger: "change" }],
    role: [{ required: true, message: "请选择岗位", trigger: "change" }],
  },
});
// 测试调用
const getList = (e) => {
  console.log("getList->", e);
};
//修改分页数
const onChanSize = (e) => {
  console.log("onChanSize->", e);
  data.queryForm.page = 1;
  data.queryForm.limit = e;
  getTableData();
};
//修改分页
const onChanPage = (e) => {
  console.log("onChanPage->", e);
  data.queryForm.page = e;
  getTableData();
};
// 查询搜索
const querySearch = (obj) => {
  console.log('querySearch->', obj);
  searchVal.value = obj
  getTableData();
};
// 获取表格数据
const getTableData = async () => {
  console.log("getTableData->", data.queryForm);
  let params = {
    pageNum: data.queryForm.page,
    pageSize: data.queryForm.limit,
    ...searchVal.value,
    orderByColumn: "projectStartTime",
  };
  if (searchVal.value === "") {
    delete params.projectName;
  } else {
    params.pageNum = 1;
    params.pageSize = data.queryForm.limit;
  }
  data.loading = true;
  const res = await getProjectList(params);
  data.loading = false;
  if (res.code === 200) {
    if (Array.isArray(res.data)) {
      data.tableData = res.data;
      data.total = res.data.length;
    } else {
      data.tableData = res.data.content;
      data.total = res.data.totalElements;
    }
  }
};
const changeFile = (rawFile, arr) => {
  if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error("最大为1MB!");
    return false;
  }
  ruleForm.binData = rawFile.name;
  fileList.value = arr;
};
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error("最大为1MB!");
    return false;
  }
  return true;
};
let imgAction = ref($httpUrl + "/file/upload");
const handleRemove = (uploadFile, uploadFiles) => {
  if (uploadFile.id == undefined) {
    let num = 0;
    fileList.value.map((item, index) => {
      if (item.uid == uploadFile.uid) {
        num = index;
      }
    });
    fileList.value.splice(num, 1);

    return false;
  }
  axios
    .delete($httpUrl + "/file", {
      data: uploadFile,
      headers: {
        "Content-Type": "application/json",
      },
    })
    .then((res) => {
      if (res.data.code == "200") {
        layer.msg("删除成功");
        let i = 0;
        fileList.value.map((item, index) => {
          if (item.id == uploadFile.id) {
            i = index;
          }
        });

        fileList.value.splice(i, 1);
      } else {
        layer.msg(res.data.message);
      }
    });
};
const handlePreview = () => { };
const showDisabled = (obj) => {
  let arr = oldUserList.filter((item) => {
    return obj.userid == item.userid;
  });
  if (arr.length > 0) {
    return false;
  } else {
    return true;
  }
};
const reQueryForm = () => {
  // 重置查询表单
  data.queryForm = {
    page: 1,
    limit: 100,
  };
};
let oldUserList = [];
let dsb = ref(0);
const getuserList = (params) => {
  // 获取表格数据
  data.loading = true;
  $axios
    .get("/user/selectAllUser", {
      page: 1,
      limit: 10000,
    })
    .then((res) => {
      oldUserList = JSON.parse(JSON.stringify(res.data.data.records));
      userOptions.value = res.data.data.records;
      dsb.value++;
    });
  data.loading = false;
};
let dialogVisibleImg = ref(false);
let dialogImageUrl = ref("");
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisibleImg.value = true;
};

const dataURLtoBlob = (dataurl) => {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {
    type: mime,
  });
};

const ruleFormRef = ref(null);
const upload = ref(null);
const submitForm = async (formEl) => {
  closeDialog();
  return false;
};
const closeDialog = () => {
  let idList = [];
  for (let i = 0; i < fileList.value.length; i++) {
    if (fileList.value[i].id) {
      idList.push(fileList.value[i].id);
    } else {
      idList.push(fileList.value[i].response.data.id);
    }
  }
  let item = JSON.parse(localStorage.getItem("idList"));
  let obj = { [imgId.value]: idList };
  localStorage.setItem("idList", JSON.stringify({ ...item, ...obj }));
  dialogTableVisible.value = false;
};
const onSuccess = () => {
  layer.msg("上传成功");
  ruleForm.binData = "";
};

const printDate = () => {
  const d = new Date();
  const year = d.getFullYear();
  const month = d.getMonth() > 8 ? d.getMonth() + 1 : "0" + (d.getMonth() + 1);
  const date = d.getDate() > 9 ? d.getDate() : "0" + d.getDate();
  const hours = d.getHours() > 9 ? d.getHours() : "0" + d.getHours();
  const minutes = d.getMinutes() > 9 ? d.getMinutes() : "0" + d.getMinutes();
  const seconds = d.getSeconds() > 9 ? d.getSeconds() : "0" + d.getSeconds();
  return `${year}-${month}-${date}T`;
};

const copy = () => {
  var clipboard = new Clipboard(".tag-read");
  clipboard.on("success", (e) => {
    // console.log('复制成功')
    layer.msg("复制成功");
    // 释放内存
    clipboard.destroy();
  });
  clipboard.on("error", (e) => {
    // 不支持复制
    // console.log('该浏览器不支持自动复制')
    // 释放内存
    clipboard.destroy();
  });
};

const isUserInput = ref(false)
const onAddressSelected = (poi) => {
  console.log("Address selected in parent component: ", poi);
  isUserInput.value = true
  data.form.latitude = poi.point.lat;
  data.form.longitude = poi.point.lng;
  data.form.address = poi.title + ", " + poi.address;
  // 在这里处理选中的地址
};

const add = () => {
  // 新增
  formState.value = "add";
  isUserInput.value = false
  data.form = {
    isUserInput: false,
    projectStartTime: printDate(),
    illuminance: "",
    originalIlluminance: "",
    investmentAmount: "",
    latitude: null,
    longitude: null,
    address: null,
    attributes: "",
    id: "",
    projectName: "",
    electricityPrice: "",
    projectLightInfos: [
      {
        amount: "",
        lightName: "",
        power: "",
      },
    ],
  };
  users.value = [];
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "新增项目" : "addItem",
    content: $("#saveOrUpdateDiv"),
    area: ["45%", "65%"],
    offset: ["100px"],
    success: function (index) {
      //清空表单数据
      // $("#dataFrm")[0].reset();
      url = $httpUrl + "/role/insertRole";
    },
  });
};

const generateData = () => {
  $axios.post("/device/getUnactiveDev", {}).then((res) => {
    dsb.value++;
    transferOld = res.data.data == null ? [] : res.data.data;
    if (res.data.data == null) {
      res.data.data = [];
    }
    res.data.data.map((item) => {
      transferdata.value.push({
        key: item.id,
        label: item.nickName,
      });
    });
  });
};
let oneDeviceArr = [];
const transferdata = ref([]);
const transfervalue = ref([]);
let oldValue = [];
let rowData = {};
let users = ref([]);
let oldUser = [];
const check = (oldUser) => {
  //userOptions.value
  let arr = userOptions.value.filter((item) => {
    return oldUser.userid == item.userid;
  });
  if (arr.length > 0) {
    return false;
  } else {
    return true;
  }
};

const fileList = ref([]);

const uniqueFunc = (arr, uniId) => {
  const res = new Map();
  return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
};
let imgId = ref("");
const uploadImg = (row) => {
  imgId.value = row.id;
  dialogTableVisible.value = true;
  ruleForm.domain = imgId.value;
  // fileList.value=[{name:"",url:"",id:""}];
  getImg();
};
const getImg = () => {
  fileList.value = [];
  $.get($httpUrl + "/file/get?domain=" + imgId.value, {}, function (res) {
    for (let i = 0; i < res.data.length; i++) {
      fileList.value.push({
        name: i + 1 + ".jpg",
        url: "data:image/jpg;base64," + res.data[i].binData,
        ...res.data[i],
      });
    }
    let temp = unique(fileList.value, "id");
    fileList.value = unique(fileList.value, "id");

    let idList = JSON.parse(localStorage.getItem("idList"));
    if (idList == null) {
      fileList.value = temp;
      return false;
    }
    let forObj = idList[imgId.value];
    let arr = [];
    if (forObj != undefined && forObj.length > 0) {
      for (let i = 0; i < forObj.length; i++) {
        let obj = fileList.value.filter((item) => {
          return item.id == forObj[i];
        });
        arr.push(obj[0]);
      }
      fileList.value = arr;
    } else {
      fileList.value = temp;
    }
  });
};

const unique = (jsonArr, field) => {
  // 数组长度小于2 或 没有指定去重字段 或 不是json格式数据
  if (jsonArr.length < 2 || !field || typeof jsonArr[0] !== "object") return jsonArr;
  const uniqueArr = jsonArr.reduce((all, next) => (all.some((item) => item[field] == next[field]) ? all : [...all, next]), []);
  return uniqueArr;
};

const edit = (row) => {
  // 编辑
  if (dsb.value != 2) {
    return false;
  }
  formState.value = 'edit'
  isUserInput.value = false
  electricMetersList.value = oldElectricMetersList;
  userOptions.value = JSON.parse(JSON.stringify(oldUserList));
  transfervalue.value = [];
  let arr = [];
  transferdata.value = [];
  rowData = row;
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "修改项目" : "Modify Project",
    content: $("#saveOrUpdateDiv"),
    area: ["45%", "92%"],
    success: function (index) {
      data.form = row;
      if (data.form.projectLightInfos == null) {
        data.form.projectLightInfos = [];
      }
      if (data.form.projectLightInfos.length == 0) {
        data.form.projectLightInfos = [
          {
            amount: "",
            lightName: "",
            power: "",
          },
        ];
      }
      axios
        .post($httpUrl + "/user/UsersByProjectId", {
          deviceFid: row.id,
        })
        .then((res) => {
          oldUser = res.data.data;
          for (let i = 0; i < res.data.data.length; i++) {
            userOptions.value.push(res.data.data[i]);
          }
          userOptions.value = uniqueFunc(userOptions.value, "userid");
          users.value = res.data.data.map((item) => {
            return item.userid;
          });
        });
      axios
        .post($httpUrl + "/device/getChildDevice", {
          deviceFid: row.id,
        })
        .then((res) => {
          oneDeviceArr = res.data.data;
          for (let i = 0; i < res.data.data.length; i++) {
            let item = res.data.data[i];
            transferdata.value.push({
              key: item.id,
              label: item.nickName,
            });
          }
          for (let i = 0; i < transferOld.length; i++) {
            transferdata.value.push({
              key: transferOld[i].id,
              label: transferOld[i].nickName,
            });
          }
          for (let i = 0; i < res.data.data.length; i++) {
            let item = res.data.data[i];
            arr.push(item.id);
          }
          transferdata.value = transferdata.value.filter(function (item, index, self) {
            return self.findIndex((el) => el.key == item.key) === index;
          });

          transferOld = transferOld.filter(function (item, index, self) {
            return self.findIndex((el) => el.id == item.id) === index;
          });

          let uniqueArray = arr.filter((item, index, array) => {
            return array.indexOf(item) === index;
          });

          oldValue = arr;
          transfervalue.value = uniqueArray;
          $("body").on("click", ".clickb", function (event) {
            $(".clickb").dblclick(function (event) {
              let index = $(this).parents(".el-transfer-panel__item").index() * 1;
              changeRight($(this).html(), index);
              event.stopPropagation();
              event.preventDefault();
              return false;
            });
          });
        });
    },
  });
};
const del = (data) => {
  ElMessageBox({
    title: "提示",
    message: h("p", null, [h("span", null, "确认删除"), h("span", { style: "color: red" }, " " + data.projectName + " "), h("span", null, "吗?")]),
    showCancelButton: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        axios
          .delete($httpUrl + "/ProjectInfo/delete", {
            data: data,
            headers: {
              "Content-Type": "application/json",
            },
          })
          .then((res) => {
            if (res.data.code == "200") {
              getTableData();
              layer.msg("删除成功");
            } else {
              layer.msg(res.data.message);
            }
            done();
          });
      } else {
        done();
      }
    },
  })
    .then((action) => { })
    .catch(() => { }); // 新增错误捕获
};
let activeName = ref("first");
let formRef = ref(null);

const submit = () => {
  // 提交新增/编辑表单
  formRef.value.validate((valid) => {
    if (valid) {
    }
  });
};

const selectRoleMenu = (data) => {
  openselectRoleMenu(data);
};

var tableIns;
var $ = "";
var layer = "";
var form = "";
var table = "";
var dtree = "";
var url = "";
var mainIndex = "";

var menuTree = "";
//打开分配菜单的弹出层
function openselectRoleMenu (data) {
  mainIndex = layer.open({
    type: 1,
    title: "分配【" + data.rolename + "】的角色",
    content: $("#selectRoleMenu"),
    area: ["400px", "450px"],
    btnAlign: "c",
    btn: ['<div class="layui-icon layui-icon-release">确认分配</div>', '<div class="layui-icon layui-icon-close">取消分配</div>'],
    yes: function (index, layero) {
      var nodes = dtree.getCheckbarNodesParam("menuTree");
      var roleid = data.roleid;
      var params = "roleid=" + roleid;

      $.each(nodes, function (i, item) {
        params += "&ids=" + item.nodeId;
      });

      //保存角色和菜单的关系
      $.post($httpUrl + "/role/saveRoleMenu", params, function (res) {
        if ((res.code = 200)) {
          layer.msg(res.msg);
          //parent.layer.closeAll();
          //"#selectRoleMenu").hide();
          layer.close(mainIndex);
        } else {
          layer.msg(res.msg);
        }
      });
    },
    success: function (index) {
      //初始化树
      menuTree = dtree.render({
        elem: "#menuTree",
        dataStyle: "layuiStyle", //使用layui风格的数据格式
        response: { message: "msg", statusCode: 0 }, //修改response中返回数据的定义
        dataFormat: "list", //配置data的风格为list
        checkbar: true, //复选框
        checkbarType: "all", // 默认就是all
        checkbarData: "choose",
        url: $httpUrl + "/role/initRoleMenuTreeJson?roleid=" + data.roleid, // 使用url加载（可与data加载同时存在）
      });
    },
  });
}
const handleClick = () => { };
let dialogVisible = ref();
let str1 = ref();
let str2 = ref();
let strId = ref();
let DeviceSecret = ref();
let textarea = ref(
  `{
    "TargetServerUri": "mqtt.qlmsmart.com",
    "Port": "1883",
    "ProductKey": "h5n2naC5o6v",
    "DeviceName": "qlm00000099",
    "UserName": "h5n2naC5o6v,qlm00000099",
    "UserPassword": "A4C69F5CB7483D20E50A53FB09CB986BFEE69E2D",
    "DeviceSecret": "acff0be4ed62dfce9e440b27d429a14b"
  }`
);

const changeRight = (key, index) => {
  let product_key = "";
  let device_name = "";
  let device_secret = "";

  // let arr = oneDeviceArr.filter((item) => {
  //   return item.nickName == key
  // })
  let arr = [oneDeviceArr[index]];
  product_key = arr[0].productKey;
  device_name = arr[0].deviceName;
  device_secret = arr[0].deviceSecret;
  strId.value = arr[0].id;
  DeviceSecret.value = arr[0].deviceSecret;

  var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode      */
  /*
   * These are the functions you'll usually want to call
   * They take string arguments and return either hex or base-64 encoded strings
   */
  function hex_hmac_sha1 (key, data) {
    return binb2hex(core_hmac_sha1(key, data));
  }

  /*
   * Calculate the SHA-1 of an array of big-endian words, and a bit length
   */
  function core_sha1 (x, len) {
    /* append padding */
    x[len >> 5] |= 0x80 << (24 - (len % 32));
    x[(((len + 64) >> 9) << 4) + 15] = len;

    var w = Array(80);
    var a = 1732584193;
    var b = -271733879;
    var c = -1732584194;
    var d = 271733878;
    var e = -1009589776;

    for (var i = 0; i < x.length; i += 16) {
      var olda = a;
      var oldb = b;
      var oldc = c;
      var oldd = d;
      var olde = e;

      for (var j = 0; j < 80; j++) {
        if (j < 16) w[j] = x[i + j];
        else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
        var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
        e = d;
        d = c;
        c = rol(b, 30);
        b = a;
        a = t;
      }

      a = safe_add(a, olda);
      b = safe_add(b, oldb);
      c = safe_add(c, oldc);
      d = safe_add(d, oldd);
      e = safe_add(e, olde);
    }
    return Array(a, b, c, d, e);
  }

  /*
   * Perform the appropriate triplet combination function for the current
   * iteration
   */
  function sha1_ft (t, b, c, d) {
    if (t < 20) return (b & c) | (~b & d);
    if (t < 40) return b ^ c ^ d;
    if (t < 60) return (b & c) | (b & d) | (c & d);
    return b ^ c ^ d;
  }

  /*
   * Determine the appropriate additive constant for the current iteration
   */
  function sha1_kt (t) {
    return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514;
  }

  /*
   * Calculate the HMAC-SHA1 of a key and some data
   */
  function core_hmac_sha1 (key, data) {
    var bkey = str2binb(key);
    if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

    var ipad = Array(16),
      opad = Array(16);
    for (var i = 0; i < 16; i++) {
      ipad[i] = bkey[i] ^ 0x36363636;
      opad[i] = bkey[i] ^ 0x5c5c5c5c;
    }

    var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
    return core_sha1(opad.concat(hash), 512 + 160);
  }

  /*
   * Add integers, wrapping at 2^32. This uses 16-bit operations internally
   * to work around bugs in some JS interpreters.
   */
  function safe_add (x, y) {
    var lsw = (x & 0xffff) + (y & 0xffff);
    var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
    return (msw << 16) | (lsw & 0xffff);
  }

  /*
   * Bitwise rotate a 32-bit number to the left.
   */
  function rol (num, cnt) {
    return (num << cnt) | (num >>> (32 - cnt));
  }

  /*
   * Convert an 8-bit or 16-bit string to an array of big-endian words
   * In 8-bit function, characters >255 have their hi-byte silently ignored.
   */
  function str2binb (str) {
    var bin = Array();
    var mask = (1 << chrsz) - 1;
    for (var i = 0; i < str.length * chrsz; i += chrsz) bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - (i % 32));
    return bin;
  }

  /*
   * Convert an array of big-endian words to a hex string.
   */
  function binb2hex (binarray) {
    var hex_tab = "0123456789ABCDEF";
    var str = "";
    for (var i = 0; i < binarray.length * 4; i++) {
      str += hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8 + 4)) & 0xf) + hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8)) & 0xf);
    }
    return str;
  }

  function onSign () {
    var pk = document.getElementById("productKey").value;
    var dn = document.getElementById("deviceName").value;
    var ds = document.getElementById("deviceSecret").value;
    var ts = document.getElementById("timestamp").value;
    var ci = document.getElementById("clientId").value;
    var jcl = document.getElementById("jcl");

    var sm = document.getElementById("signMethod").value;
    var us = document.getElementById("username");
    var pw = document.getElementById("password");

    var ul = document.getElementById("url");
    var ar = document.getElementById("area").value;

    us.value = dn + "&" + pk;

    //jcl.value = 'ssss';
    jcl.value = ci + "|securemode=3,signmethod=hmacsha1,timestamp=" + ts + "|";
    //alert((ci+'|securemode=3,signmethod=hmacsha1,timestamp='+ts+'|'));
    ul.value = pk + ".iot-as-mqtt." + ar + ".aliyuncs.com:1883";
    if (pk == null || pk == "" || dn == null || dn == "" || ds == null || ds == "" || ci == null || ci == "") {
      alert("productKey,deviceName,deviceSecret,clientId can not be empty");
      return;
    }
    var options = {
      productKey: pk,
      deviceName: dn,
      timestamp: ts,
      clientId: ci,
    };
    if (ts == null || ts == "") {
      options = {
        productKey: pk,
        deviceName: dn,
        clientId: ci,
      };
    }
    var keys = Object.keys(options).sort();
    // 按字典序排序
    keys = keys.sort();
    var list = [];
    keys.forEach(function (key) {
      list.push(key + options[key]);
    });
    var contentStr = list.join("");
    var sign = "";
    if (sm == "hmacmd5") {
      sign = hex_hmac_md5(ds, contentStr);
    } else if (sm == "hmacsha1") {
      sign = hex_hmac_sha1(ds, contentStr);
    } else {
      alert("method is invalid");
    }
    pw.value = sign.toUpperCase();
  }
  function test (options, ds) {
    var keys = Object.keys(options).sort();
    // 按字典序排序
    keys = keys.sort();
    var list = [];
    keys.forEach(function (key) {
      list.push(key + options[key]);
    });
    var contentStr = list.join("");
    var sign = "";
    sign = hex_hmac_sha1(ds, contentStr);
    return sign;
  }
  function test2 (product_key, device_name, device_secret) {
    let options = {
      productKey: product_key,
      deviceName: device_name,
      clientId: "12345",
    };
    return "AT+MQTT_PWD=" + test(options, device_secret);
  }
  str1.value = test2(product_key, device_name, device_secret);
  str2.value = "AT+MQTT_KEYNAME=" + product_key + "," + device_name;
  dialogVisible.value = true;

  let pwd = test2(product_key, device_name, device_secret).replaceAll("AT+MQTT_PWD=", "");
  let textareaObj = {
    TargetServerUri: "mqtt.qlmsmart.com",
    Port: "1883",
    ProductKey: product_key,
    DeviceName: device_name,
    UserName: product_key + "," + device_name,
    UserPassword: pwd,
    DeviceSecret: arr[0].deviceSecret,
  };
  textarea.value = JSON.stringify(textareaObj);
  textarea.value = JSON.stringify(JSON.parse(textarea.value), null, "\t");
};
let transferOld = [];
const changeTransfer = (str, st) => {
  if (st == "right") {
    showRight(str, st);
  } else {
    showLeft(str, st);
  }
};
const showLeft = (str, st) => {
  let obj = [];
  if (str.length == 0) {
    obj = oldValue;
  } else {
    obj = oldValue.filter((el) => !str.includes(el));
  }
  let list = [];
  for (let i = 0; i < obj.length; i++) {
    let arr = oneDeviceArr.filter((item) => {
      return item.id == obj[i];
    });
    list.push(arr[0]);
  }
  for (let i = 0; i < list.length; i++) {
    if (list[i]) {
      list[i].fid = 135;
      list[i].deviceStatus = "UNACTIVE";
    }
  }
  for (let i = 0; i < list.length; i++) {
    $axios.post("/device/updateDevice", list[i]).then((res) => {
      layer.msg("操作成功");
      if (i == list.length - 1) {
        axios
          .post($httpUrl + "/device/getChildDevice", {
            deviceFid: rowData.id,
          })
          .then((res) => {
            oneDeviceArr = res.data.data;
          });
      }
    });
  }
};
const showRight = () => {
  let obj = [];
  for (let i = 0; i < transfervalue.value.length; i++) {
    let arr = transferOld.filter((item) => {
      return item.id == transfervalue.value[i];
    });
    obj.push(arr[0]);
  }
  for (let i = 0; i < obj.length; i++) {
    if (obj[i]) {
      obj[i].fid = rowData.id;
      obj[i].deviceStatus = "OFFLINE";
    }
  }
  // console.log("参数", obj);
  for (let i = 0; i < obj.length; i++) {
    if (obj[i]) {
      $axios.post("/device/updateDevice", obj[i]).then((res) => {
        layer.msg("操作成功");
        if (i == obj.length - 1) {
          axios
            .post($httpUrl + "/device/getChildDevice", {
              deviceFid: rowData.id,
            })
            .then((res) => {
              oneDeviceArr = res.data.data;
            });
        }
      });
    }
  }
};

const syntaxHighlight = (json) => {
  if (typeof json != "string") {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    var cls = "number";
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        cls = "key";
      } else {
        cls = "string";
      }
    } else if (/true|false/.test(match)) {
      cls = "boolean";
    } else if (/null/.test(match)) {
      cls = "null";
    }
    return '<span class="' + cls + '">' + match + "</span>";
  });
};

const addPower = () => {
  data.form.projectLightInfos.push({ amount: "", power: "", lightName: "" });
};
const subtractionbtnPower = (i) => {
  if (i == 0 && data.form.projectLightInfos.length == 1) {
    return false;
  }
  data.form.projectLightInfos.splice(i, 1);
};
let dialogVisible3 = ref(false);
let pwd = ref("");
const checkTime = () => {
  dialogVisible3.value = true;
};
let pwdFlag = ref(false);
let projectStartTime = ref();
const enterPwd = () => {
  if (pwd.value == "") {
    ElMessage({
      type: "error",
      message: "请输入密码",
    });
    return;
  }
  let params = {
    pwd: pwd.value,
  };
  axios.post($httpUrl + "/sel/authorization", params).then((res) => {
    if (res.data.data) {
      ElMessage({
        type: "success",
        message: `密码正确可以修改`,
      });
      dialogVisible3.value = false;
      pwd.value = "";
      pwdFlag.value = true;
      projectStartTime.value.focus();
    } else {
      ElMessage({
        type: "error",
        message: "密码错误不能修改",
      });
    }
  });
};

let imei = ref();
let oldElectricMetersList = [];
let electricMetersList = ref([]);
const getElectricMetersList = () => {
  $axios.post("/access/electricMeters", {}).then((res) => {
    electricMetersList.value = res.data.data;
    oldElectricMetersList = res.data.data;
  });
};
let companyList = ref([]);
const getcompany = () => {
  $axios.get("/company", {}).then((res) => {
    companyList.value = res.data.data;
  });
};

const projectstate = [
  { id: 1, projectstate: "建设中" },
  { id: 2, projectstate: "运行中" },
];

onMounted(() => {
  getcompany();
  getElectricMetersList();
  generateData();
  getuserList();
  layui
    .extend({
      dtree: "/layui_ext/dist/dtree",
    })
    .use(["jquery", "layer", "form", "table", "dtree"], function () {
      $ = layui.jquery;
      layer = layui.layer;
      form = layui.form;
      table = layui.table;
      dtree = layui.dtree;
      //保存
      form.on("submit(doSubmit)", function (obj) {
        console.log();
        if (data.form.projectName == "") {
          layer.msg("项目名称不能为空");
          return false;
        }
        if (formState.value === 'add') {
          data.form.projectStartTime = globalProperties.$dayjs(new Date()).format("YYYY-MM-DD") + 'T00:00:00'
        } else {
          if (data.form.projectStartTime == "") {
            layer.msg("请选择项目启动日期");
            return false;
          }
        }

        if (data.form.attributes == "") {
          layer.msg("客户属性不能为空");
          return false;
        }
        if (users.value.length == 0 && data.form.id) {
          layer.msg("请选择所属所属用户");
          return false;
        }
        // 项目地址为为空【告诉后端校验字段】
        data.form.isUserInput = isUserInput.value
        //序列化表单数据
        var params = JSON.parse(JSON.stringify(data.form));
        if (params.id == "") {
          params.projectStartTime = params.projectStartTime;
        }
        if (!params.id) {
          delete params.id;
        }
        params.iotDeviceList = oneDeviceArr;
        axios.put($httpUrl + "/ProjectInfo/saveOrUpdate", params).then((res) => {
          if (res.data.code == "200") {
            layer.close(mainIndex);
            layer.msg("保存成功");
            getTableData();
            let arrUser = [];
            let arrDeviceInfoList = [];
            for (let j = 0; j < users.value.length; j++) {
              for (let i = 0; i < userOptions.value.length; i++) {
                if (userOptions.value[i].userid == users.value[j]) {
                  arrUser.push(userOptions.value[i]);
                  break;
                }
              }
            }
            let params2 = {
              deviceFid: data.form.id,
              users: arrUser,
              deviceInfoList: oneDeviceArr,
            };
            axios.put($httpUrl + "/UserDevices", params2).then((res) => {
              if (res.data.code == "200") {
                layer.msg("保存成功");
              } else {
                layer.msg(res.data.message);
              }
            });
          } else {
            layer.msg(res.data.message);
          }
        });
      });
    });
  getTableData();
});
</script>
<style lang="scss">
.ProjectList {}
</style>
<style lang="scss" scoped>
.drag_img {
  display: flex;
  width: 100%;
  flex-wrap: wrap;

  .img_item {
    height: 110px;
    width: 110px;
    padding: 0px 10px 10px 0;
    box-sizing: border-box;
    position: relative;
    cursor: move;
  }
}

.shade {
  cursor: move;
  position: absolute;
  left: 0;
  top: 0;
  right: 10px;
  bottom: 10px;
  text-align: center;
  padding: 0 10px 10px 0;
  color: #fff;
  opacity: 0;
  box-sizing: border-box;
  font-size: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  -webkit-transition: opacity 0.3s;
  transition: opacity 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;

  .img_operate {
    padding: 10px 0 0 10px;
  }

  &:hover {
    opacity: 1;
  }
}

.layui-input-block {
  margin-left: 140px;
}

.layui-form-label {
  width: 110px;
}

.available1 {
  color: orangered;
}

#menuToolBar {
  display: flex;
  justify-content: left;
  align-items: left;
  flex: 1;
  padding-left: 20px;
}

:deep(.el-input__wrapper) {
  background: none;
  color: #fff;
}

:deep(#dataFrm .el-input__inner) {
  color: #fff;
}

:deep(.el-transfer-panel) {
  background: none;
}

:deep(.el-transfer-panel .el-transfer-panel__header) {
  background: none;
  color: #fff;
}

:deep(.el-transfer-panel .el-transfer-panel__header .el-checkbox .el-checkbox__label) {
  color: #fff;
}

:deep(.el-transfer) {
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
  justify-content: left;
  float: left;
}

:deep(.el-transfer__buttons) {
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
}

:deep(.el-transfer__button) {
  margin: 0 10px;
  transform: rotate(-180deg);
}

:deep(.el-transfer-panel__item.el-checkbox .el-checkbox__label span) {
  color: #fff;
  position: relative;
}

.tipsT {
  padding: 8px 6px;
  border: solid 1px #ddd;
  margin-bottom: 10px;
  font-size: 14px;
}

.tag-read {
  color: var(--el-color-primary);
  float: right;
}

.tipsBox {
  padding: 3px;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
  background: rgba(33, 112, 147, 0.3);
}

.lab {
  color: #fff;
  padding: 0 12px;
  display: inline-block;
}

.ruleFormlist {
  margin-bottom: 10px;
}

.timeBtn {
  display: block;
  width: 100%;
  opacity: 0;
  position: relative;
  height: 33px;
  z-index: 99;
}

.timeBtnBox {
  position: relative;
}

:deep(.timeDate) {
  position: absolute;
  top: 0;
}

a.dsb {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
<style>
.projectManagement {
  display: flex !important;
}

.layui-layer-shade {
  z-index: 11 !important;
}

.layui-layer-page {
  z-index: 1111 !important;
}

.clickb {
  display: inline-block;
  width: 149px;
  height: 18px;
  position: absolute;
  left: -2px;
  top: 0px;
}

pre {
  outline: 1px solid #ccc;
  padding: 5px;
  margin: 5px;
}

.string {
  color: green;
}

.number {
  color: darkorange;
}

.boolean {
  color: blue;
}

.null {
  color: magenta;
}

.key {
  color: red;
}

#saveOrUpdateDiv .layui-form-item {
  float: left;
  width: 50%;
  clear: none;
  margin-bottom: 12px;
}
</style>
